package com.xiangmo.travel.Controller;

import com.xiangmo.travel.Annotation.TokenRequired;
import com.xiangmo.travel.Dto.ResultData;
import com.xiangmo.travel.Dto.ScoreDto;
import com.xiangmo.travel.Dvo.ScoreStatusDvo;
import com.xiangmo.travel.Enums.CodeAndMsg;
import com.xiangmo.travel.Service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/score")
public class ScoreController {
    @Autowired
    private ScoreService scoreService;

    /**
     * 查询用户评分状态
     * @param attractionsId 景点id
     * @param userId 用户id
     * @param token
     * @return
     */
    @TokenRequired
    @GetMapping("/{attractionsId}/{userId}")
    public ResultData<ScoreStatusDvo> getStatus(@PathVariable Long attractionsId, @PathVariable Long userId, @RequestHeader("Authorization") String token){
        Integer starNum = scoreService.getStarNum(attractionsId, userId);
        ScoreStatusDvo scoreStatusDvo = new ScoreStatusDvo();
        if(starNum != 0){
            scoreStatusDvo.setStatus(1);
            scoreStatusDvo.setStarNum(starNum);
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(), CodeAndMsg.SUCCESS.getMessage(),
                    scoreStatusDvo, token.substring(7));
        }
        scoreStatusDvo.setStatus(0);
        return new ResultData<>(CodeAndMsg.SUCCESS.getCode(), CodeAndMsg.SUCCESS.getMessage(),
                scoreStatusDvo, token.substring(7));
    }

    /**
     * 修改评分
     * @param token
     * @return
     */
    @TokenRequired
    @PutMapping()
    public ResultData<ScoreStatusDvo> setStarNum(@RequestBody ScoreDto scoreDto, @RequestHeader("Authorization") String token){
        Long userId = scoreDto.getUserId();
        Integer starNum = scoreDto.getStarNum();
        Long attractionsId = scoreDto.getAttractionsId();
        Integer status = 0;
        //查询该评分存在？
        Integer is = scoreService.isStarNum(attractionsId, userId);
        if(is <= 0){
            //新增
            status = scoreService.insertScore(scoreDto);
        }else {
            //修改
            status = scoreService.setStarNum(attractionsId, userId, starNum);
        }
        //修改成功
        if(status > 0){
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(), CodeAndMsg.SUCCESS.getMessage(),
                    null, token.substring(7));
        }
        return new ResultData<>(CodeAndMsg.ERROR.getCode(), CodeAndMsg.ERROR.getMessage(),
                null, token.substring(7));
    }
}
